# -*- coding: UTF-8 -*-
from . import api
from flask import request
from app import util
from dbConnection.MysqlConn import Mysql
import sys
reload(sys)
sys.setdefaultencoding('utf8')


# 根据车牌获取用户uid
@api.route('/user/get_uid', methods=['post'])
def get_uid():
    data = {}
    data['code'] = util.CODE_EMPTY
    data['data'] = {}
    try:
        plate = request.values.get('plate')
        sql = "select u.uid, u.wxNickName, u.wxHeadImg FROM car_plate p LEFT JOIN car_users u ON u.uid = p.uid WHERE " \
              "p.license_plate = '%s'" % plate
        mysql = Mysql()
        res = mysql.getOne(sql, None)
        mysql.dispose()
        if res:
            data['code'] = util.CODE_SUCCESS
            data['data'] = res
    except Exception as e:
        print e
        data['code'] = 500
    return util.to_json(data)


# 获取用户的套餐
@api.route('/api/user_recharge', methods=['post'])
def user_recharge():
    data = {}
    data['code'] = util.CODE_EMPTY
    data['data'] = []
    try:
        openId = request.values.get('openId')
        sql = "select t.recharge_name, t.recharge_num, t.use_num, t.add_time, t.source_type, t.end_time, t.give_uid, " \
              "if(now() > t.end_time, 0, 1) card_flag, t.id FROM user_taocan t LEFT JOIN car_users u ON u.uid = t.uid " \
              "WHERE u.wxOpenId = '%s' ORDER BY t.add_time desc" % openId
        sql2 ="select * FROM user_business"
        mysql = Mysql()
        res = mysql.getAll(sql, None)
        business = mysql.getAll(sql2, None)
        mysql.dispose()
        maps = {}
        if business:
            for k in business:
                maps[str(k['bid'])] = k['nickname']
        if res:
            for d in res:
                d['add_time'] = str(d['add_time'])
                d['end_time'] = str(d['end_time'])
                d['username'] = ''
                if d['source_type'] == 2 and maps.has_key(str(d['give_uid'])):
                    d['username'] = maps[str(d['give_uid'])]
            data['code'] = util.CODE_SUCCESS
            data['data'] = res
    except Exception as e:
        print e
        data['code'] = util.CODE_ERROR
    return util.to_json(data)


# 获取用户车牌列表
@api.route('/user/plate_list', methods=['post'])
def plate_list():
    data = {}
    data['code'] = util.CODE_EMPTY
    data['data'] = []
    try:
        openId = request.values.get('openId')
        sql = "select p.license_plate, p.id, p.add_time FROM car_plate p LEFT JOIN car_users u ON p.uid = u.uid WHERE" \
              " u.wxOpenId = '%s'" % openId
        mysql = Mysql()
        res = mysql.getAll(sql, None)
        mysql.dispose()
        if res:
            data['code'] = util.CODE_SUCCESS
            for d in res:
                d['add_time'] = str(d['add_time'])
            data['data'] = res
    except Exception as e:
        print e
        data['code'] = 500
    return util.to_json(data)


# 修改用户车牌
@api.route('/user/update_plate', methods=['post'])
def update_plate():
    data = {}
    data['code'] = 201  # 操作失败
    data['msg'] = '操作失败'
    try:
        openId = request.values.get('openId')
        pid = request.values.get('pid')
        plate = request.values.get('plate')
        con = get_cp(plate)
        if con:
            data['code'] = 202
            data['msg'] = '车牌已绑定'
            return util.to_json(data)
        res = user_update_plate(openId, pid, plate)
        if res > 0:
            data['code'] = 200
            data['msg'] = '操作成功'
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 用户绑定车牌
@api.route('/user/bind_plate', methods=['post'])
def bind_plate():
    data = {}
    data['code'] = 201
    data['msg'] = '操作失败'
    try:
        openId = request.values.get('openId')
        plate = request.values.get('plate')
        user = get_user_plate_num(openId)
        if user is None:
            data['code'] = 202
            data['msg'] = '用户不存在'
            return util.to_json(data)
        if int(user['user_cp']) >= 3:
            data['code'] = 203
            data['msg'] = '一个用户最多绑定3辆车'
            return util.to_json(data)
        con = get_cp(plate)
        if con:
            data['code'] = 204
            data['msg'] = '车牌已绑定'
            return util.to_json(data)
        res = user_insert_cp(user['uid'], plate)
        if res > 0:
            data['code'] = 200
            data['msg'] = '操作成功'
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 用户删除车牌
@api.route('/user/delete_plate', methods=['post'])
def delete_plate():
    data = {}
    data['code'] = 201
    data['msg'] = '操作失败'
    try:
        openId = request.values.get('openId')
        pid = request.values.get('pid')
        user = get_user_detail(openId)
        if user is None:
            data['code'] = 201
            data['msg'] = '用户不存在'
            return util.to_json(data)
        res = user_delete_plate(pid, user['uid'])
        if res > 0:
            data['code'] = 200
            data['msg'] = '操作成功'
    except Exception as e:
        print e
        data['code'] = 500
        data['msg'] = '系统错误'
    return util.to_json(data)


# 查询车牌是否已绑定
def get_cp(cp_num):
    sql = "select * FROM car_plate WHERE license_plate = '%s'" % str(cp_num).upper()
    print sql
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 用户更改车牌
def user_update_plate(openid, pid, plate):
    sql = "update car_plate p LEFT join car_users c ON c.uid = p.uid SET p.license_plate = '%s' WHERE p.id = '%s' " \
          "AND c.wxOpenId = '%s'" % (plate, pid, openid)
    mysql = Mysql()
    res = mysql.update(sql, None)
    mysql.dispose()
    return res


# 查询用户已绑定的车牌数
def get_user_plate_num(openid):
    sql = "select u.uid, if(c.nums, c.nums, 0) AS user_cp FROM car_users u LEFT JOIN (SELECT count(*) nums, uid " \
          "FROM car_plate GROUP BY uid) c ON c.uid = u.uid WHERE u.wxOpenId = '%s'" % openid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 用户新增车牌
def user_insert_cp(uid, plate):
    sql = "insert INTO car_plate(uid, license_plate, add_time) VALUES ('%s', '%s', now())" % (uid, plate)
    mysql = Mysql()
    res = mysql.insertOne(sql, None)
    mysql.dispose()
    return res


# 查询用户
def get_user_detail(openid):
    sql = "select uid FROM car_users WHERE wxOpenId = '%s'" % openid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 用户删除车牌
def user_delete_plate(pid, uid):
    sql = "delete FROM car_plate WHERE id = '%s' AND uid = '%s'" % (pid, uid)
    mysql = Mysql()
    res = mysql.delete(sql, None)
    mysql.dispose()
    return res